import { defineStore } from 'pinia';
import { getBanners, getHotProducts } from '../api/home.js';

export const useHomeStore = defineStore('home', {
  state: () => ({
    // 轮播图列表
    banners: [],
    // 热销商品列表
    hotProducts: [],
    // 数据加载状态
    loading: {
      banners: false,
      hotProducts: false
    },
    // 数据刷新时间戳
    refreshTime: {
      banners: 0,
      hotProducts: 0
    },
    // 热销商品显示数量
    hotProductLimit: 10
  }),

  getters: {
    // 获取轮播图列表
    getBannerList: (state) => state.banners.map(item => ({
      ...item,
      image: item.image_url
    })),
    // 获取热销商品列表
    getHotProductList: (state) => state.hotProducts,
    // 判断数据是否正在加载
    isLoading: (state) => (type) => state.loading[type],
    // 获取数据最后更新时间
    getLastRefreshTime: (state) => (type) => state.refreshTime[type]
  },

  actions: {
    // 加载轮播图数据
    async loadBanners() {
      if (this.loading.banners) return;
      
      try {
        this.loading.banners = true;
        const res = await getBanners();
        if (res.code === 200) {
          // 处理轮播图数据格式
          this.banners = (res.data || []).map(item => ({
            id: item.id,
            image_url: item.image_url,
            link: item.link || '/pages/promotion/index',
            title: item.title || ''
          }));
          this.refreshTime.banners = Date.now();
        }
        return res;
      } catch (error) {
        console.error('加载轮播图失败:', error);
        throw error;
      } finally {
        this.loading.banners = false;
      }
    },

    // 加载热销商品数据
    async loadHotProducts(limit) {
      if (this.loading.hotProducts) return;
      
      try {
        this.loading.hotProducts = true;
        const actualLimit = limit || this.hotProductLimit;
        const res = await getHotProducts(actualLimit);
        
        if (res.code === 200) { 
          // 处理热销商品数据格式
          this.hotProducts = (res.data || []).map(item => ({
            id: item.id,
            title: item.name,
            img_url: item.imageUrl,
            price: item.price || 0,
            unit: item.specifications || '',
            description: item.description || '',
            number: item.sales || 0,
            categoryId: item.categoryId,
            categoryName: item.categoryName,
            isHot: item.isHot || 0,
            isRecommend: item.isRecommend || 0,
            origin: item.origin || '',
            shelfLife: item.shelfLife || '',
            storageMethod: item.storageMethod || '',
            stock: item.stock || 0,
            discountPrice: item.discountPrice || item.price
          }));
          this.refreshTime.hotProducts = Date.now();
        }
        return res;
      } catch (error) {
        console.error('加载热销商品失败:', error);
        throw error;
      } finally {
        this.loading.hotProducts = false;
      }
    },

    // 设置热销商品显示数量
    setHotProductLimit(limit) {
      this.hotProductLimit = limit;
    },

    // 刷新所有首页数据
    async refreshHomeData() {
      try {
        await Promise.all([
          this.loadBanners(),
          this.loadHotProducts()
        ]);
      } catch (error) {
        console.error('刷新首页数据失败:', error);
        throw error;
      }
    },

    // 清空首页数据
    clearHomeData() {
      this.banners = [];
      this.hotProducts = [];
      this.refreshTime.banners = 0;
      this.refreshTime.hotProducts = 0;
    }
  }
});
